package com.aaa.ssm.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @date ：Created in 2023/10/16 16:07
 * @description：登录过滤器，拦截非法用户，或者session过期用户
 * @modified By：
 * @version: 1.0
 */
@WebFilter("/html/*")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    private String[] urls = new String[]{
          "front-home.html", "codelogin.html", "userenroll.html", ".js", ".css", ".png", ".jpg", "login.html","userlogin.html", "login", "createVCodeAndSendSmsSave"
    };

    /**
     * 做过滤器
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {


        //session中有userInfo放行，否则调转到登录页面
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String url = httpServletRequest.getRequestURI();
        //验证是否需要拦截
        boolean r = false;
        for (String u : urls) {
            if (url.endsWith(u)) {
                //放行
                r = true;
                break;
            }
        }
        if (r) {
            //不需要效验
            chain.doFilter(request, response);
        } else {
           //需要校验是否登录
            if (httpServletRequest.getSession().getAttribute("userInfo") == null) {
                HttpServletResponse servletResponse = (HttpServletResponse) response;
                servletResponse.sendRedirect("/html/front-home.html");
            } else {
           //放行
                chain.doFilter(request, response);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
